package com.openlogic.common.db.api.client;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Stopwatch;
import com.openlogic.common.db.api.provider.JDBCDataSourceProvider;
import com.openlogic.common.spi.datasource.DataSourceClient;
import com.openlogic.common.spi.enums.DbType;
import com.openlogic.datasource.api.param.BaseConnectionParam;
import com.zaxxer.hikari.HikariDataSource;

import jodd.db.connection.DataSourceConnectionProvider;
import jodd.db.oom.DbOomQuery;

public class CommonDataSourceClient implements DataSourceClient {

    private static final Logger logger = LoggerFactory.getLogger(CommonDataSourceClient.class);

    public static final String COMMON_USER = "root";
    public static final String COMMON_VALIDATION_QUERY = "select 1";
    
    protected final BaseConnectionParam baseConnectionParam;
    protected HikariDataSource dataSource;
//    protected JdbcTemplate jdbcTemplate;
    protected DataSourceConnectionProvider connectionProvider;
    

    public CommonDataSourceClient(BaseConnectionParam baseConnectionParam, DbType dbType) {
        this.baseConnectionParam = baseConnectionParam;
        preInit();
        checkEnv(baseConnectionParam);
        initClient(baseConnectionParam, dbType);
        checkClient();
    }

    protected void preInit() {
        logger.info("preInit in CommonDataSourceClient");
    }

    protected void checkEnv(BaseConnectionParam baseConnectionParam) {
        checkValidationQuery(baseConnectionParam);
        checkUser(baseConnectionParam);
    }

    protected void initClient(BaseConnectionParam baseConnectionParam, DbType dbType) {
        this.dataSource = JDBCDataSourceProvider.createJdbcDataSource(baseConnectionParam, dbType);
        this.connectionProvider = new DataSourceConnectionProvider(dataSource);
    }

    protected void checkUser(BaseConnectionParam baseConnectionParam) {
        if (StringUtils.isBlank(baseConnectionParam.getUser())) {
            setDefaultUsername(baseConnectionParam);
        }
    }

    protected void setDefaultUsername(BaseConnectionParam baseConnectionParam) {
        baseConnectionParam.setUser(COMMON_USER);
    }

    protected void checkValidationQuery(BaseConnectionParam baseConnectionParam) {
        if (StringUtils.isBlank(baseConnectionParam.getValidationQuery())) {
            setDefaultValidationQuery(baseConnectionParam);
        }
    }

    protected void setDefaultValidationQuery(BaseConnectionParam baseConnectionParam) {
        baseConnectionParam.setValidationQuery(COMMON_VALIDATION_QUERY);
    }

    @Override
    public void checkClient() {
        //Checking data source client
        Stopwatch stopwatch = Stopwatch.createStarted();
        try {
			DbOomQuery.query(connectionProvider.getConnection(), this.baseConnectionParam.getValidationQuery()).find();
        } catch (Exception e) {
            throw new RuntimeException("JDBC connect failed", e);
        } finally {
            logger.info("Time to execute check jdbc client with sql {} for {} ms ", this.baseConnectionParam.getValidationQuery(), stopwatch.elapsed(TimeUnit.MILLISECONDS));
        }
    }

    @Override
    public Connection getConnection() {
        try {
            return this.dataSource.getConnection();
        } catch (SQLException e) {
            logger.error("get druidDataSource Connection fail SQLException: {}", e.getMessage(), e);
            return null;
        }
    }

    @Override
    public void close() {
        logger.info("do close dataSource {}.", baseConnectionParam.getDatabase());
        try (HikariDataSource closedDatasource = dataSource) {
        	connectionProvider.close();
        	dataSource.close();
        }
        this.connectionProvider = null;
    }

	@Override
	public boolean valid() throws SQLException {
		return this.getConnection().isValid(0);
	}

}
